<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/16 0016
 * Time: 12:31
 */

namespace frontend\controllers;



use common\models\Userr;
use frontend\tool\Tool;
use Yii;
class CheckLogin
{
    private $APPID = 'wx7646ca6bb92fa339';
    private $appsecret = '2584e088977867de01b1015def0ea45d';
    public static  $key = '123';     // 密钥
    public function check(){
        $lifeTime = 24 * 3600;//  保存一天
        session_set_cookie_params($lifeTime);
        session_id("NowaMagic");
        session_start();
        $_SESSION['users']=array('name'=>111,'sid'=>session_id());
    }
    //请求授权页面
    public function actionScopeRedirectUriAppid()
    {
        $param = Yii::$app->request->get();

        //var_dump($param['id']);die;

       // $REDIRECT_URI = 'http://xiaochaoyang.cn/Blog/frontend/web/index.php?r='.$param['r'].'&id='.$param['id'];

        $REDIRECT_URI = 'http://xiaochaoyang.cn/Blog/frontend/web/index.php';
        $scope = 'snsapi_userinfo';  //手动授权snsapi_userinfo   静默授权snsapi_base

        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->APPID . '&redirect_uri=' . $REDIRECT_URI . '&response_type=code&scope=' . $scope . '&state=1234';

        header("Location:{$url}" );
        exit;

    }
    public function getAccesstion($code){
        $requestData = [
            'appid'  => $this->APPID,
            'secret'   => $this->appsecret,
            'code'  => $code,
            'grant_type' => 'authorization_code'
        ];

        $cchReqOpt = [
            'timeOut'=>3,
        ];
        $ReqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $reqResult = Tool::sendRequest($ReqUrl,$requestData,$cchReqOpt);
        if ($reqResult['state'] == 1){
            $data = json_decode($reqResult['data'],TRUE);
            $this->getOpenId($data['access_token'],$data['openid']);

        }


    }
    public function getOpenId($token,$openid){
        $requestData = [
            'access_token'  => $token,
            'openid'   => $openid,

        ];

        $cchReqOpt = [
            'timeOut'=>3,
        ];
        $ReqUrl = 'https://api.weixin.qq.com/sns/userinfo';
        $reqResult = Tool::sendRequest($ReqUrl,$requestData,$cchReqOpt);
        $data = json_decode($reqResult['data'],TRUE);
        $user = Userr::find()->where(['openid'=>$data['openid']])->one();
        if ($user){
            $user->wxname = $data['nickname'];
            $user->province = $data['province'];
            $user->city =$data['city'];
            $user->sex = $data['sex'];
            $user->province = $data['province'];
            $user->city =$data['city'];
            $user->icon = $data['headimgurl'];
            $user->updated_at =time();
            $user->update();
            $username = $user->username;
        }
        else{
            $res = new Userr();
            $res->openid = $data['openid'];
            $res->username = Tool::getRandomStr();
            $res->wxname = $data['nickname'];
            $res->sex = $data['sex'];
            $res->province = $data['province'];
            $res->city =$data['city'];
            $res->icon = $data['headimgurl'];
            $res->created_at = time();
            $res->updated_at =time();
            $res->save();
            $username = $res->username;
        }
        $msg = $data['openid'];  // 被加密信息
        $encrypt = md5($msg.CheckLogin::$key);
        $this->makeSession($encrypt,$username);

    }
    public function makeSession($meg,$username){
        $lifeTime = 24 * 3600;//  保存一天
        session_set_cookie_params($lifeTime);
        session_id($meg);
        session_start();

        $_SESSION['users'] = array('username'=>$username,'sid'=>session_id());
    }



     public function encrypt($data, $key)
    {
        $key = md5($key);
        $x  = 0;
        $char = '';
        $str = '';
        $len = strlen($data);
        $l  = strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }
    public function decrypt($data, $key)
    {
        $key = md5($key);
        $x = 0;
        $char ='';
        $str = '';
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
            {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }
            else
            {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }


}